#!/usr/bin/python
# -*-coding:utf-8-*-
from urllib.error import HTTPError
from urllib.request import urlopen
from urllib.request import Request
from urllib import parse
from bs4 import BeautifulSoup as bs
import pymysql.cursors
import os.path


class music_sq688:
    def __init__(self, id=None, singer=None, title=None, suffix=None, url=None, password=None, size=None,
                 release_date=None,
                 lyrics=None):
        self.id = id
        self.singer = singer
        self.title = title
        self.suffix = suffix
        self.url = url
        self.password = password
        self.size = size
        self.release_date = release_date
        self.lyrics = lyrics


def replace(ma):
    # 获取数据连接
    connection = pymysql.connect(host="127.0.0.1", user="root", password="root", db="common", charset="utf8mb4")
    cursor = connection.cursor()
    try:
        # 创建sql语句
        sql = "replace into `music_sq688` (`id`,`title`,`singer`,`suffix`,`url`,`password`,`size`,`release_date`,`lyrics`) " \
              "values(%s,%s,%s,%s,%s,%s,%s,%s,%s)"
        # 执行sql语句
        cursor.execute(sql, (
            ma.id, ma.title, ma.singer, ma.suffix, ma.url, ma.password, ma.size, ma.release_date, ma.lyrics))
        # 提交
        connection.commit()
    except Exception as e:
        # 错误回滚
        connection.rollback()
    finally:
        connection.close()


if __name__ == "__main__":
    for x in range(24563, 30000):  # 7357
        url = "https://www.sq688.com/download/%s.html" % x
        try:
            # 获得服务器返回的数据
            response = urlopen(url)
            # 处理数据
            page = response.read().decode("utf-8")
            soup = bs(page, "html.parser")
            ma = music_sq688()
            ma.id = x
            for child in soup.select("div.dcenter div[style='position:relative;left:20px;overflow:hidden;']"):
                ma.title = child.h2.text.split(" ")[0]
                ma.suffix = child.h2.select_one("span.cb").text
                ma.singer = child.select("p")[0].text
                ma.size = child.select("p")[1].text
                ma.release_date = child.select("p")[2].text

            sa = soup.select("div.dcenter div.url")
            for child in soup.select("div.dcenter div.url"):
                if len(child.select("p.downurl"))>0:
                    ma.url = child.select_one("input.path").get("value")
                    ma.password = child.select_one("button#openurl").get("data-clipboard-text")
            print((ma.id, ma.singer, ma.title, ma.suffix, ma.size, ma.url, ma.password, ma.release_date))
            replace(ma)
        except AttributeError as ae:
            print("ID：%s 网页获取失败：%s" % (url, ae))
        except HTTPError as http:
            print("ID：%s 网页获取失败：%s" % (url, http.msg))
